<?php
namespace App\Services\RoomScore;

use App\Models\MainDB\RoomPit;

class RoomUserGiftScoreService{

    /**
     * 房间麦位信息(接口返回与推送的数据模型)
     * @param int $roomId
     * @return array
     */
    public function roomSeats(int $roomId): array
    {
        $response = [];
        $query = RoomPit::query();
        //$query->lockForUpdate();
        $query->where("user_id", ">", 0);
        $query->where("room_id", $roomId);
        $query->with(["user"]);
        $models = $query->get();
        $userIds = array_filter(array_column($models->toArray(), "user_id"));

        // map
        $roomUserServer = new RoomUserServer();
        $users = $roomUserServer->users($roomId, $userIds);

        foreach ($models as $model) {
            $countdown = $model->countdown - time();
            $user = null;
            $userId = $model->user_id;
            if (!empty($model->user)) {
                $user = $users[$userId];
                $user['is_singing'] = $model->is_singing ?? 0;
            }
            $response[] = [
                "number" => $model->number,
                "user_id" => $userId,
                "user" => $user,
                "type" => $model->type,
                "voice_switch" => $model->voice_switch,
                "stream_switch" => $model->stream_switch,
                "countdown" => $countdown > 0 ? $countdown : 0,
                "is_open" => $model->is_open,
            ];
        }

        return $response;
    }

    /**
     * 房间麦位信息(接口返回与推送的数据模型)
     * @param int $roomId
     * @return array
     */
    public function RecommendRoomSeats(int $roomId): array
    {
        $response = [];
        $query = RoomPit::query();
        //$query->lockForUpdate();
        $query->where("user_id", ">", 0);
        $query->where("room_id", $roomId);
        $query->with(["user"]);
        $models = $query->get();
        $userIds = array_filter(array_column($models->toArray(), "user_id"));

        // map
        $roomUserServer = new RoomUserServer();
        $users = $roomUserServer->users($roomId, $userIds);

        foreach ($models as $model) {
            $user = null;
            $userId = $model->user_id;
            if (!empty($model->user)) {
                $user = $users[$userId];
                $user['is_singing'] = $model->is_singing ?? 0;
            }
            if ($model->number == 9){
                array_unshift($response,[
                    "number"  => $model->number,
                    "user_id" => $userId,
                    "user"    => $user,
                ]);
            }else{
                $response[] = [
                    "number"  => $model->number,
                    "user_id" => $userId,
                    "user"    => $user,
                ];
            }
        }

        return array_slice($response,0,5);
    }
}
